package com.controller;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.BaseControllers;
import com.google.gson.Gson;
import com.model.Urls;
import com.model.XiaocaiIpTimesInfo;
import com.model.XiaocaiUrls;
import com.model.XiaocaiWorkInfo;
import com.service.UrlsService;
import com.service.XiaocaiUrlsService;
import com.service.impl.RedisBase;

/**
 * 控控制层
 */
@Controller
@RequestMapping("/urls")
public class UrlsController extends BaseControllers {
	@Resource
	private UrlsService urlsService;
	@Resource
	private XiaocaiUrlsService xiaocaiUrlsService;
	@Resource
	private RedisBase redisBase;

	@RequestMapping(value = "/index")
	public ModelAndView index() {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("user/user", context);
	}

	/*
	 * @RequestMapping("/jump") public void jump(HttpServletRequest request,
	 * HttpServletResponse response) throws Exception { // 获取要跳转的网址 Urls urls =
	 * new Urls(); List<Urls> listUrls = urlsService.selectByCriteria(urls);
	 * response.sendRedirect("http://www.baidu.com"); }
	 */

	@RequestMapping("/src_{randId}")
	public void srcJumpUrl(@PathVariable long randId,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		XiaocaiUrls xiaocaiUrls = xiaocaiUrlsService.getRandomUrls();
		if (null != xiaocaiUrls) {
			Random random=new Random();
			String src=xiaocaiUrls.getSourceUrls();
			String []srcArray=src.split("\n");
			if(null!=srcArray&&srcArray.length>0)
				response.sendRedirect(srcArray[random.nextInt(srcArray.length)]);
			// 记录当前访问的IP地址（设置1分钟过期？）
			String keyString = "customer_" + "randId_" + String.valueOf(randId)
					+ "_ip_" + this.getIpAddr(request).replace(".", "_");
			Gson gson = new Gson();
			String json=gson.toJson(xiaocaiUrls);
			redisBase.STRINGS.setEx(keyString, 600, String.valueOf(json));
			return;
		}else 
		response.sendRedirect("http://www.baidu.com/#wd=%E6%98%9F%E4%BA%91%E6%B5%81%E9%87%8F%E7%AB%99");
	}
	
	@RequestMapping("/target_{randId}")
	public void targetJumpUrl(@PathVariable long randId,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String keyString = "customer_" + "randId_" + String.valueOf(randId)
				+ "_ip_" + this.getIpAddr(request).replace(".", "_");
		String json=redisBase.STRINGS.get(keyString);
		Gson gson = new Gson();
		XiaocaiUrls xiaocaiUrls=gson.fromJson(json, XiaocaiUrls.class);
		if (null != xiaocaiUrls) {
			response.sendRedirect(xiaocaiUrls.getTargetUrl());
			return;
		}
		response.sendRedirect("http://www.xyllz.com/urls/jump/3");
	}
	/**
	 * 小菜流量系统跳转
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/jump/{userId}")
	public void jumpUrl(@PathVariable long userId, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		XiaocaiUrls xiaocaiUrls = xiaocaiUrlsService.getRandomUrls();
		if (null != xiaocaiUrls) {
			response.sendRedirect(xiaocaiUrls.getTargetUrl());
			XiaocaiWorkInfo xiaocaiWorkInfo = new XiaocaiWorkInfo();
			xiaocaiWorkInfo.setUrlId(xiaocaiUrls.getUrlId());
			xiaocaiWorkInfo.setPoint(1);
			xiaocaiWorkInfo.setUserId(userId);
			xiaocaiWorkInfo.setUrlsBelongToUserId(xiaocaiUrls.getUserIdP());
			// 获取当前小时
			Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
			int hour = c.get(Calendar.HOUR_OF_DAY);
			xiaocaiWorkInfo.setFinishedHour(hour);
			Gson gson = new Gson();
			// 对此链接进行减分操作
			String keyString = "urlId_"
					+ String.valueOf(xiaocaiUrls.getUrlId()) + "_userId_"
					+ String.valueOf(userId);
//			redisBase.HASH.hset("urls_sql", keyString,
//					gson.toJson(xiaocaiWorkInfo));
			redisBase.LISTS.lpush("urls_sql",gson.toJson(xiaocaiWorkInfo));
			// 记录当前访问人刷的次数
			keyString = "userId_" + String.valueOf(userId);
			XiaocaiIpTimesInfo xiaocaiIpTimesInfoOld = (XiaocaiIpTimesInfo) gson
					.fromJson(redisBase.HASH.hget("urls_minute", keyString),
							XiaocaiIpTimesInfo.class);
			XiaocaiIpTimesInfo xiaocaiIpTimesInfo = new XiaocaiIpTimesInfo();
			xiaocaiIpTimesInfo.setUserId(userId);
			if (null == xiaocaiIpTimesInfoOld) {
				xiaocaiIpTimesInfo.setClickCount(1);
			} else {
				xiaocaiIpTimesInfo.setClickCount(xiaocaiIpTimesInfoOld
						.getClickCount() + 1);
			}
			redisBase.HASH.hset("urls_minute", keyString,
					gson.toJson(xiaocaiIpTimesInfo));
			// 记录当前访问的IP地址（设置1分钟过期？）
			keyString = "customer_" + "userId_" + String.valueOf(userId)
					+ "_ip_" + this.getIpAddr(request).replace(".", "_");
			redisBase.STRINGS.setEx(keyString, 61, String.valueOf(1));
		}
	}

	@RequestMapping(value = "/jump.json")
	@ResponseBody
	public Map jump_json(String name) {
		if (StringUtils.isEmpty(name))
			throw new RuntimeException();
		return Collections.singletonMap("name", name);
	}

	@RequestMapping(value = "/show.json")
	@ResponseBody
	public Map jsonShow(String name) {
		// if(StringUtils.isEmpty(name) ) throw new RuntimeException();
		return Collections.singletonMap("name", "李培峰");
	}

	@RequestMapping(value = "/showftl")
	public String showftl() {
		Map<String, Object> context = new HashMap<String, Object>();
		return "showftl";
	}
}
